package androidcamp.socialfitnesstracker;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import androidcamp.socialfitnesstracker.util.TimeInterval;

import java.util.concurrent.Semaphore;

public class WorkoutActivityTimer implements Runnable {

    public static final String LOG_TAG = "WorkoutActivityTimer";
    
    private long elapsedTime;
    private Semaphore elapsedTimeSemaphore;
    private Handler mHandler;
    
    private TextView timeView;
    private static final int TICK = 1;

    public WorkoutActivityTimer(TextView paramTimeView) {
        super();
        Log.d(LOG_TAG, "initialized");
        elapsedTime = 0;
        elapsedTimeSemaphore = new Semaphore(1);
        timeView = paramTimeView;
        mHandler = new Handler() {
            public void handleMessage(Message paramMessage) {
                Log.d(LOG_TAG, "handle message: " + paramMessage.toString());
                try {
                    switch (paramMessage.what) {
                        case TICK:
                            WorkoutActivityTimer.this.elapsedTimeSemaphore.acquire();
                            TimeInterval interval = new TimeInterval(elapsedTime);
                            WorkoutActivityTimer.this.timeView
                                    .setText(String.format("%02d:%02d:%02d",
                                            interval.getHours(), interval.getMinutes(), interval.getSeconds()));
                            WorkoutActivityTimer.this.elapsedTimeSemaphore.release();
                    }
                } catch (InterruptedException e) {
                    Log.e(LOG_TAG, "View update interrupted!");
                }
            }
        };
    }

    public void run() {
        try {
            while(true) {
                Log.d(LOG_TAG, "tick");
                elapsedTimeSemaphore.acquire();
                elapsedTime += 1;
                elapsedTimeSemaphore.release();
                mHandler.sendEmptyMessage(TICK);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            Log.e(LOG_TAG, "Timer interrupted!");
            return;
        }
    }

    public long getElapsedTime() throws InterruptedException {
        elapsedTimeSemaphore.acquire();
        long time = elapsedTime;
        elapsedTimeSemaphore.release();
        return time;
    }

}
